package com.itheima.case2.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

//@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1.获取请求的方法名
            String uri = request.getRequestURI();
            //2.获取指定索引后的方法名
            int index = uri.lastIndexOf("/");
            //3.从指定位置截取到方法结尾
            String methodName = uri.substring(index + 1);
            //4.通过this关键字获取当前类的class对象
            Class<?> clazz = this.getClass();
            //5.获取要执行方法
            Method m = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //6.暴力反射
            m.setAccessible(true);
            //7.执行方法
            m.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}